package controller

import (
	"github.com/gin-gonic/gin"
	"github.com/samber/lo"
	"k9-panel/app/adapter/internal"
	"k9-panel/app/adapter/internal/convert"
	"k9-panel/app/model"
	"k9-panel/app/permission"
	"k9-panel/app/response"
	"k9-panel/app/service"
	"k9-panel/pkg/gslice"
	"net/http"
)

var (
	Environment *EnvironmentController
)

func init() {
	Environment = new(EnvironmentController)
}

type EnvironmentController struct {
	common
}

func (t *EnvironmentController) List(c *gin.Context) {
	list, err := service.Environment.List()
	if err != nil {
		panic(err)
	}

	envs := lo.Map(list, func(item *model.Environment, _ int) *internal.EnvRsp {
		return convert.EnvModel2EnvRsp(item)
	})
	user, err := t.GetLoginUser(c)
	if err != nil {
		panic(err)
	}
	if !user.Super {
		envIds, err := permission.Perm.GetOwnEnvIDs(c, user.Username, service.Environment)
		if err != nil {
			panic(err)
		}
		envs = lo.Filter(envs, func(item *internal.EnvRsp, index int) bool {
			return gslice.InSlice(envIds, item.ID)
		})
	}
	c.JSON(http.StatusOK, response.Success(envs))
	return
}
func (t *EnvironmentController) Projects(c *gin.Context) {
	var (
		list internal.PrimaryParam
	)
	err := c.ShouldBind(&list)
	if err != nil {
		panic(err)
	}
	env, err := service.Environment.Get(list.Id)
	if err != nil {
		panic(err)
	}

	c.JSON(http.StatusAccepted, gin.H{"list": env.Projects})
	return
}
func (t *EnvironmentController) Add(c *gin.Context) {
	var (
		env model.Environment
	)
	err := c.BindJSON(&env)
	if err != nil {
		panic(err)
	}
	id, err := service.Environment.Create(&env)
	if err != nil {
		panic(err)
	}
	c.JSON(http.StatusAccepted, gin.H{"id": id})
	return
}
func (t *EnvironmentController) Batch(c *gin.Context) {
	var (
		env []*model.Environment
	)
	err := c.BindJSON(&env)
	if err != nil {
		panic(err)
	}
	ids := make([]uint, 0)
	for _, v := range env {
		id, err := service.Environment.Create(v)
		if err != nil {
			panic(err)
		}
		ids = append(ids, id)
	}

	c.JSON(http.StatusOK, response.Success(ids))
	return
}
func (t *EnvironmentController) Delete(c *gin.Context) {
	var (
		env model.Environment
	)
	err := c.BindJSON(&env)
	if err != nil {
		panic(err)
	}
	affected, err := service.Environment.Delete(&env)
	if err != nil {
		panic(err)
	}
	if affected == 0 {
		c.JSON(http.StatusOK, response.Fail[string]("删除失败！"))
	} else {
		c.JSON(http.StatusOK, response.Success[string]("删除成功！"))
	}

	return
}
func (t *EnvironmentController) Update(c *gin.Context) {
	var (
		env model.Environment
	)
	err := c.BindJSON(&env)
	if err != nil {
		panic(err)
	}
	affected, err := service.Environment.Update(&env)
	if err != nil {
		panic(err)
	}
	if affected == 0 {
		c.JSON(http.StatusOK, response.Fail[string]("更新失败！"))
	} else {
		c.JSON(http.StatusOK, response.Success[string]("更新成功！"))
	}

	return
}
